package com.hxzy.gateway.filter;


import com.hxzy.framework.common.constant.AuthConstant;
import com.hxzy.gateway.properties.IgnoreUrlProperties;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;


/**
 * jwt远程过滤器，排除的验证地址
 * @author 11452
 */
@Component
public class IgnoreUrlsRemoveJwtFilter implements WebFilter {
    /**
     * 读取忽略的url地址配置
     */
    @Resource
    private IgnoreUrlProperties ignoreUrlProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //得到当前请求url
        URI uri = request.getURI();
        String path = uri.getPath();

        PathMatcher pathMatcher = new AntPathMatcher();
        //获取所有忽略地址
        List<String> ignoreUrls = ignoreUrlProperties.getUrls();

        for (String ignoreUrl : ignoreUrls) {
            //如果当前请求地址在忽略地址里面
            if (pathMatcher.match(ignoreUrl, path)) {
                //把请求头认证删除掉， 不需要令牌
                request = exchange.getRequest().mutate().header(AuthConstant.JWT_TOKEN_HEADER, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }
}
